package com.cpos.orderserver.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.RegistrationBean;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @创建人 Leiwenlong
 * @创建时间 2020/11/5 0005
 * @描述
 **/
@RestController
public class OrderContrller {

    Logger logger = LoggerFactory.getLogger(OrderContrller.class);

    //服务注册
    @Autowired
    Registration registration;

    //服务发现客户端
    @Autowired
    DiscoveryClient discoveryClient;

    @RequestMapping("/buy")
    public String buyOrder() {
        ServiceInstance instance = serviceInstance();
        //打印服务的服务id
        logger.info("*********" + instance.getServiceId());
        return "hello,this is order-service 您购买了一件商品！";
    }

    public ServiceInstance serviceInstance() {
        List<ServiceInstance> list = discoveryClient.getInstances(registration.getServiceId());
        if (list != null && list.size() > 0) {
            for (ServiceInstance itm : list) {
                if (itm.getPort() == 9090) {
                    return itm;
                }
            }
        }
        return null;
    }

}
